package cn.edu.scau.cmi.linjinyong.fxml.springMybatis;

import cn.edu.scau.cmi.linjinyong.fxml.mybatis.MybatisController;
import cn.edu.scau.cmi.linjinyong.fxml.mybatis.TeacherData;
import cn.edu.scau.cmi.linjinyong.mybatis.dao.StudentDao;
import cn.edu.scau.cmi.linjinyong.mybatis.dao.TeacherDao;
import cn.edu.scau.cmi.linjinyong.mybatis.domain.Teacher;
import cn.edu.scau.cmi.linjinyong.mybatis.factory.SessionFactory;
import cn.edu.scau.cmi.linjinyong.spring.ApplicationContextFactory;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

public class SelectTeacherController {
    @FXML
    private TableView<TeacherData> teacherDataTableView;
    @FXML
    private TableColumn<TeacherData, Long> teacherIdColumn;
    @FXML
    private TableColumn<TeacherData, String> teacherNameColumn;

    private ObservableList<TeacherData> teacherDataObservableList;
    @FXML
    private Button submitButton;
    private StudentDao studentDao = (StudentDao) ApplicationContextFactory.getApplicationContext().getBean("studentDao");
    private TeacherDao teacherDao = (TeacherDao) ApplicationContextFactory.getApplicationContext().getBean("teacherDao");

    @FXML
    private void initialize(){
        teacherDataObservableList = FXCollections.observableArrayList();
        List<Teacher> teachers = teacherDao.listTeachers();
        ArrayList<TeacherData> teacherData = new ArrayList<>(teachers.size());
        teachers.forEach(t->{
            teacherData.add(new TeacherData(t));
        });
        teacherDataObservableList.addAll(teacherData);
        teacherIdColumn.setCellValueFactory(new PropertyValueFactory<TeacherData, Long>("id"));
        teacherNameColumn.setCellValueFactory(new PropertyValueFactory<TeacherData, String>("name"));
        teacherDataTableView.setItems(teacherDataObservableList);
    }

    @FXML
    public void clickTableView() {
        TeacherData selectedTeacher = teacherDataTableView.getSelectionModel().getSelectedItem();
        if(selectedTeacher != null) {
            MybatisController.getTeacher().setId(selectedTeacher.getId());
            submitButton.setDisable(false);
        }
    }

    @FXML
    private void clickSubmitButton(){
        studentDao.chooseInstructor(MybatisController.getStudent().getId(), MybatisController.getTeacher().getId());
        Stage stage = (Stage) submitButton.getScene().getWindow();
        stage.close();
    }
}
